<template>
  <el-dialog
    class="pg-shaohuo-person-edit-admin-group-rule"
    title="配置规则"
    :before-close="beforeDialogClose"
    :visible.sync="dialogVisible"
    width="50%">

    <el-tree
      :data="dataList"
      ref="tree"
      show-checkbox
      node-key="id"
      :default-expanded-keys="expandedKeys"
      :default-checked-keys="checkedKeys"
      :props="defaultProps">
    </el-tree>

    <!-- 底部按钮区
    -------------------------- -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogClose">取 消</el-button>
      <el-button type="primary"
        @click="editComplete"
        :loading="loadingBtn === '确定'">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { SettingPermissionService } from 'services/Api'
import {
  btnLoadingMixin,
  dialogCoreMixin
} from 'services/Public'
import { mapState } from 'vuex'

export default {
  mixins: [
    btnLoadingMixin,
    dialogCoreMixin
  ],
  data () {
    return {
      dataList: [],
      checkedKeys: [],
      expandedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      }
    }
  },
  props: {
    editData: Object // 编辑时原来的数据
  },
  watch: {
    editData: {
      immediate: true,
      deep: true,
      handler (v) {
        if (!v || !Object.keys(v).length) return
        const getChildren = arr => {
          if (arr.length) {
            return arr.map(item => {
              item.checked && this.checkedKeys.push(item.id)
              const children = v.rules.filter(i => i.pid === item.id)
              item.children = getChildren(children)
              return item
            })
          } else {
            return arr
          }
        }
        const parents = v.rules.filter(i => i.pid === '0')
        this.expandedKeys = parents.map(i => i.id)
        this.dataList = getChildren(parents)
      }
    }
  },
  computed: {
    ...mapState([ 'acc_id' ]),
    groupSetaccessParam () {
      return {
        acc_id: this.acc_id,
        group_id: this.editData.id,
        rules: this.$refs.tree.getCheckedKeys().join(',')
      }
    }
  },
  methods: {
    // 关闭弹窗前重置表单
    beforeDialogClose () {
      this.dataList = []
      this.checkedKeys = []
      this.expandedKeys = []
      this.dialogVisible = false
    },
    editComplete () {
      this.AsyncLoading('确定', this.groupSetaccess)
    },
    // 编辑规则接口
    async groupSetaccess () {
      const [ err ] = await SettingPermissionService.groupSetaccess(this.groupSetaccessParam)
      if (err) return this.$message.error('操作失败')
      this.$message.success(`配置成功`)
      this.dialogClose()
    }
  }
}
</script>

<style lang="scss">
@import "src/styles/config/views.scss";

@include b(shaohuo-person-edit-admin-group-rule) {
  .el-form-item__content > .el-input {
    width: 80%;
  }
}
</style>
